package algorithm.sort;

public class HeapSort implements Sort {
    @Override
    public String name() {
        return "原地最大堆排序";
    }

    @Override
    public void sort(Integer[] arr) {
        int n = arr.length;
        for (int i = (n - 1) / 2; i >= 0; i--) {
            shiftDown(arr,i,n);
        }

        for (int i = n-1; i >0; i--) {
            swap(arr,0,i);
            shiftDown(arr,0,i);
        }
        System.out.println("OK");
    }

    private void shiftDown(Integer[] arr, int index, int count) {

        while (index*2+1<count){
            int j = index*2+1;
            if (j+1<count && arr[j]<arr[j+1]){
                j++;
            }
            if (arr[index]<arr[j]){
                swap(arr,index,j);
            }else{
                break;
            }
            index=j;
        }
    }


}
